#                ,            
#   _  _/_ __    __   _   _  
#  /_)_(__/ (__(_/ (_(_/_/_)_
#                   .-/      
#                  (_/       
#
#  http://stringswiki.com
#  Understanding the simplicity
#  Copyright 2009, Asbjorn Enge. All rights reserved.
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
#  MA  02111-1307  USA
#
#  (C) 2009
"""

	thread.py - Threading support


"""
__author__  = 'Asbjorn Enge <asbjorn@hanafjedle.net>'

import threading, webob

class Localized(object):
	""" Threading support
	"""
	def __init__(self):
		self.local = threading.local()
		
	def register(self, object):
		self.local.object = object
		
	def unregister(self):
		del self.local.object
		
	def __call__(self):
		try:
			return self.local.object
		except AttributeError:
			raise TypeError("No object has been registered for this event")

get_request = Localized()

class RegisterRequest(object):
	""" For registering requests with thread
	"""
	def __init__(self, app):
		self.app = app
		
	def __call__(self, environ, start_response):
		req = webob.Request(environ)
		get_request.register(req)
		try:
			return self.app(environ, start_response)
		finally:
			get_request.unregister()
